package com.example.qiandao.service;

import com.example.qiandao.entity.User;

import com.example.qiandao.repository.UserRepository;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    @Value("${wx.appid}")
    private String wxAppId;

    @Value("${wx.secret}")
    private String wxSecret;

    private static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";


    /**
     * 微信登录逻辑
     */
    public Map<String, Object> wxLogin(String code) {
        // 调用微信接口获取 openid 和 session_key
        String url = String.format(WX_LOGIN_URL, wxAppId, wxSecret, code);
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.getForObject(url, String.class);

        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode;
        try {
            jsonNode = objectMapper.readTree(response);
        } catch (IOException e) {
            throw new RuntimeException("Failed to parse WeChat response");
        }

        String openid = jsonNode.get("openid").asText();
        String sessionKey = jsonNode.get("session_key").asText();

        // 查询用户是否存在
        User user = userRepository.findByOpenid(openid);
        if (user == null) {
            // 用户不存在，创建新用户
            user = new User();
            user.setOpenid(openid);
            user.setRole(0); // 默认角色
            userRepository.save(user);
        }

        // 返回登录结果
        Map<String, Object> result = new HashMap<>();
        result.put("status", "success");
        result.put("userId", user.getId());
        result.put("sessionKey", sessionKey);
        result.put("name", user.getName());
        result.put("role", user.getRole());
        return result;
    }

    /**
     * 用户注册逻辑
     */
    public String register(Long userId, String name, Integer role) {
        // 根据 userId 查询用户
        User user = userRepository.findById(userId).orElse(null);
        if (user == null) {
            throw new IllegalArgumentException("User not found");
        }
        // 更新用户信息
        user.setRole(role);
        user.setName(name);
        userRepository.save(user);
        // 返回成功结果
        return "User registered successfully";
    }

    /**
     * 根据班级 ID 查询该班级下的所有学生
     */
    public List<User> getStudentsByClassId(Long classId) {

        // 查询该班级下的所有学生
        return userRepository.findByClassId(classId);
    }
}